import { Method, ResponseType, AxiosTransformer } from "axios";
import instance from "@/server/instanceAxios";
import { BASE_URL } from "@/utils/utils";
interface AxiosRequest {
  baseURL?: string;
  url: string;
  data?: any;
  params?: any;
  method?: Method;
  headers?: any;
  timeout?: number;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  responseType?: ResponseType;
}

interface AxiosResponse {
  data: any;
  headers: any;
  request?: any;
  status: number;
  statusText: string;
  config: AxiosRequest;
  success: boolean;
  total: number;
  token: string;
  detail: string;
  message: string;
}

const service = async ({
  headers,
  method,
  url,
  data,
  responseType,
  baseURL,
  transformRequest,
  params,
}: AxiosRequest): Promise<AxiosResponse> => {
  return new Promise((resolve, reject) => {
    instance({
      baseURL: baseURL ? baseURL : BASE_URL, //这边加上你具体的请求地址
      headers,
      method,
      url,
      data,
      responseType,
      transformRequest,
      params,
    }).then((res: any) => {
      try {
        const { success } = res;
        if (success) {
          resolve({
            ...res,
            success: true,
            message: "success",
            data: res?.data,
          });
        } else {
          if (responseType === "blob") {
            resolve({ ...res, success: true, message: "success", data: res });
          } else {
            resolve({
              ...res,
              status: false,
              message: res.data?.message || res?.message,
              data: res?.data,
            });
          }
        }
      } catch (e) {
        reject({ success: false, data: null, message: e });
      }
    });
  });
};

export const post = ({
         baseURL,
         url,
         data,
         responseType,
         params,
         transformRequest,
       }: AxiosRequest): Promise<AxiosResponse> => {
         return service({
           baseURL,
           url,
           data,
           method: "post",
           responseType,
           params,
           transformRequest,
         });
       };

export const get = ({
  baseURL,
  url,
  data,
  responseType,
  transformRequest,
  params,
}: AxiosRequest): Promise<AxiosResponse> => {
  return service({
    baseURL,
    url,
    data,
    method: "get",
    responseType,
    transformRequest,
    params,
  });
};
